package com.example.contact;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class Contact extends AppCompatActivity {
    ListView lv = null;
    ArrayList<Member> list;
    SqliteOpenHelper helper = new SqliteOpenHelper(Contact.this);
    EditText name = null;
    EditText phoneNumber = null;
    EditText address = null;
    EditText age = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.contact);

        lv = findViewById(R.id.lv);
        name = findViewById(R.id.name);
        phoneNumber = findViewById(R.id.phonenumber);
        address = findViewById(R.id.address);
        age = findViewById(R.id.age);

        SqliteOpenHelper helper = new SqliteOpenHelper(Contact.this);
        helper.getWritableDatabase();

//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });
    }

    void clear()
    {
        name.setText("");
        phoneNumber.setText("");
        address.setText("");
        age.setText("");
    }
    class MyAdapt extends BaseAdapter{

        //返回ListView中显示条目的数量
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        //返回ListView中显示的组件
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View view1 = View.inflate(Contact.this, R.layout.layout, null);
            TextView Name = view1.findViewById(R.id.textname);
            TextView Number = view1.findViewById(R.id.phoneNumber);
            TextView Address = view1.findViewById(R.id.Address);
            TextView Age = view1.findViewById(R.id.Age);
            Name.setText(list.get(i).getName().toString().trim());
            Number.setText(list.get(i).getNumber().toString().trim());
            Address.setText(list.get(i).getAddress().toString().trim());
            Age.setText(String.valueOf(list.get(i).getAge()));
            return view1;
        }
    }
    public void add(View view){
        SQLiteDatabase db = helper.getWritableDatabase();

        // 获取输入值
        String nameInput = name.getText().toString().trim();
        String phoneNumberInput = phoneNumber.getText().toString().trim();
        String addressInput = address.getText().toString().trim();
        String ageInput = age.getText().toString().trim();

        ContentValues values = new ContentValues();
        //输入数据
        values.put("name", nameInput);
        values.put("phonenumber", phoneNumberInput);
        values.put("address", addressInput);
        values.put("age", Integer.valueOf(ageInput));
        Log.e("main", "add: " + nameInput + phoneNumberInput + addressInput + ageInput);
        long x = db.insert("contact", null, values);

        if(x > 0){
            Toast.makeText(Contact.this, "添加成功", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(Contact.this, "添加失败", Toast.LENGTH_SHORT).show();
        }
        clear();
    }
    public void search(View view) {
        Log.e("aaa", "cursor");
        list = new ArrayList<Member>();
        SQLiteDatabase db = helper.getWritableDatabase();

        // 获取输入值
        String nameInput = name.getText().toString().trim();
        String phoneNumberInput = phoneNumber.getText().toString().trim();
        String addressInput = address.getText().toString().trim();
        String ageInput = age.getText().toString().trim();

        if (!ageInput.isEmpty() && !ageInput.matches("\\d+")) {
            Log.e("Input Error", "Age must be a valid integer");
            return; // 处理无效输入
        }
        // 构建查询条件
        StringBuilder selection = new StringBuilder();
        List<String> selectionArgs = new ArrayList<>();

        // 根据输入动态添加查询条件
        if (!nameInput.isEmpty()) {
            selection.append("name=?");
            selectionArgs.add(nameInput);
        }
        if (!phoneNumberInput.isEmpty()) {
            if (selection.length() > 0) selection.append(" AND "); // 添加 AND
            selection.append("phonenumber=?");
            selectionArgs.add(phoneNumberInput);
        }
        if (!addressInput.isEmpty()) {
            if (selection.length() > 0) selection.append(" AND "); // 添加 AND
            selection.append("address=?");
            selectionArgs.add(addressInput);
        }
        if (!ageInput.isEmpty()) {
            if (selection.length() > 0) selection.append(" AND "); // 添加 AND
            selection.append("age=?");
            selectionArgs.add(ageInput);
        }

        // 如果没有输入任何条件，执行查询所有内容
        Cursor cursor;
        if (selection.length() == 0) {
            cursor = db.query("contact", null, null, null, null, null, null); // 查询所有内容
        } else {
            cursor = db.query("contact", null,
                    selection.toString(), // 查询条件
                    selectionArgs.toArray(new String[0]), // 查询参数
                    null,
                    null,
                    null);
        }

        while (cursor.moveToNext()) {
            String Name = cursor.getString(0);
            String PhoneNumber = cursor.getString(1);
            String Address = cursor.getString(2);
            int Age = cursor.getInt(3);
            Member member = new Member(Name, PhoneNumber, Address, Age);
            list.add(member);
        }

        lv.setAdapter(new MyAdapt());
        cursor.close(); // 关闭 Cursor
        db.close(); // 关闭数据库
        clear();
    }
    public void delete(View view) {
        SQLiteDatabase db = helper.getWritableDatabase();
        String nameInput = name.getText().toString().trim();

        if (nameInput.isEmpty()) {
            Toast.makeText(this, "请输入要删除的姓名", Toast.LENGTH_SHORT).show();
            return;
        }

        int rowsDeleted = db.delete("contact", "name=?", new String[]{nameInput});
        if (rowsDeleted > 0) {
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "未找到联系人", Toast.LENGTH_SHORT).show();
        }
        db.close(); // 关闭数据库
        clear();
    }

    public void modify(View view) {
        SQLiteDatabase db = helper.getWritableDatabase();
        String nameInput = name.getText().toString().trim();
        String phoneNumberInput = phoneNumber.getText().toString().trim();
        String addressInput = address.getText().toString().trim();
        String ageInput = age.getText().toString().trim();

        if (nameInput.isEmpty()) {
            Toast.makeText(this, "请输入要修改的姓名", Toast.LENGTH_SHORT).show();
            return;
        }

        ContentValues values = new ContentValues();
        if (!phoneNumberInput.isEmpty()) {
            values.put("phonenumber", phoneNumberInput);
        }
        if (!addressInput.isEmpty()) {
            values.put("address", addressInput);
        }
        if (!ageInput.isEmpty()) {
            values.put("age", Integer.valueOf(ageInput));
        }

        int rowsUpdated = db.update("contact", values, "name=?", new String[]{nameInput});
        if (rowsUpdated > 0) {
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "未找到联系人", Toast.LENGTH_SHORT).show();
        }
        db.close(); // 关闭数据库
        clear();
    }

}